<template>
  <el-card shadow="hover" class="game-card">
    <img :src="game.imageUrl" class="game-image" />
    <div class="game-info">
      <h3>{{ game.name }}</h3>
      <el-button type="primary" @click="viewGame(game.id)">详情</el-button>
      <!-- 红心按钮 -->
      <el-button
        :type="isLiked(game.id) ? 'danger' : 'text'"
        @click="toggleLike(game.id)"
      >
        <el-icon :size="20" v-show="!isLiked(game.id)"><Star /></el-icon>
        <el-icon :size="20" v-show="isLiked(game.id)"><StarFilled /></el-icon>
      </el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { defineProps } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Star, StarFilled } from '@element-plus/icons-vue';
import request from '../axios/request';
import { useAuthStore } from '../stores/userStore'; // 确保路径正确
import { ElMessage } from 'element-plus';

const props = defineProps({ game: Object });
const router = useRouter();
const route = useRoute();
const store = useAuthStore();

const likedGames = ref([]); // 用户喜欢的游戏ID列表
const game = props.game;

// 页面键
const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${route.path || '/gamelist'}-${Math.random().toString(36).substr(2, 9)}`;
});

// 获取当前用户
const currentUser = computed(() => store.getActiveUser(pageKey.value));

// 查看游戏详情
const viewGame = (id) => {
  router.push(`/game/${id}`);
};

// 判断游戏是否被喜欢
const isLiked = (gameId) => {
  return likedGames.value.includes(gameId);
};

const selectFavorites = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录或用户ID无效');
    router.push('/');
    return;
  }
  try {
    const res = await request({
      url: `/favorites/list?userId=${user.id}`,
      method: 'get',
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      game.value = res.data.data || [];
      console.log('喜欢游戏:', res.data.data);
    } else {
      ElMessage.error('获取喜欢游戏失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求失败，请检查网络');
    if (err.message === '登录已失效，请重新登录') {
      router.push('/');
    }
  }
};

// 获取用户喜欢的游戏
const getLikedGames = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    console.error('当前用户未定义或ID无效');
    return;
  }
  try {
    const res = await request({
      url: '/favorites/getLikedGames?userId='+user.id,
      method: 'post',
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      likedGames.value = res.data.data || [];
      console.log('喜欢的游戏:', likedGames.value);
    } else {
      console.error('获取喜欢的游戏失败:', res.data.msg);
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
  }
};

// 添加到喜欢列表
const addToFavorites = async (gameId) => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录，无法添加喜欢');
    return;
  }
  try {
    const res = await request({
      url: '/favorites/add',
      method: 'post',
      data: {
        userId: user.id,
        gameId: gameId,
      },
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      likedGames.value.push(gameId);
      console.log('添加喜欢成功');
      ElMessage.success('已添加到喜欢');
    } else {
      console.error('添加喜欢失败:', res.data.msg);
      ElMessage.error('添加喜欢失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求失败，请检查网络');
  }
};

// 从喜欢列表中移除
const removeFromFavorites = async (gameId) => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录，无法取消喜欢');
    return;
  }
  try {
    const res = await request({
      url: '/favorites/delete',
      method: 'post',
      data: {
        userId: user.id,
        gameId: gameId,
      },
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      likedGames.value = likedGames.value.filter((id) => id !== gameId);
      selectFavorites();
      console.log('取消喜欢成功');
      ElMessage.success('已取消喜欢');
    } else {
      console.error('取消喜欢失败:', res.data.msg);
      ElMessage.error('取消喜欢失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求失败，请检查网络');
  }
};

// 切换喜欢状态
const toggleLike = async (gameId) => {
  if (isLiked(gameId)) {
    await removeFromFavorites(gameId);
  } else {
    await addToFavorites(gameId);
  }
};

// 初始化
onMounted(() => {
  store.initialize();
  console.log('Page Key on Mounted:', pageKey.value);
  console.log('Page Users on Mounted:', store.pageUsers);
  const storedPageKey = sessionStorage.getItem('pageKey');
  if (storedPageKey) {
    const user = store.getActiveUser(pageKey.value);
    if (user && user.id) {
      getLikedGames();
    } else {
      console.error('用户未登录，无法加载喜欢的游戏');
    }
  } else {
    console.log('会话未初始化，等待登录');
  }
});
</script>

  <style scoped>
.game-card {
  position: relative;
  width: 250px;
  margin: 10px;
}

.game-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
}

.game-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.el-button {
  margin-left: 10px;
}

  .game-card {
    border-radius: 10px;
    overflow: hidden;
  }
  
  .game-image {
    width: 100%;
    height: 180px;
    object-fit: cover;
  }
  
  .game-info {
    text-align: center;
    margin-top: 10px;
  }
  </style>
  